<?php


namespace app\index\controller;


use app\admin\model\ResourceRecommend;
use app\admin\model\UsersMember;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use wxpay\Wxsend;

/**
 * 定时脚本
 * Class AutoWork
 * @package app\index\controller
 */
class TimedTask extends Base
{
    /**
     * 检索栏-社群推荐
     */
    public static function search_recommended()
    {
        self::recommendedList(10, 1);
    }

    /**
     * 固定栏-社群推荐
     */
    public static function fixed_recommended()
    {
        self::recommendedList(10, 2);
    }

    /**
     * 处理社群推荐 5分钟更新一条 上限10条  type值：1=>检索栏推荐 2=>固定栏推荐
     * @param $limit
     * @param $type
     * @param int $time
     */
    private static function recommendedList($limit, $type, $time = 320)
    {
        // 删除过期数据
        ResourceRecommend::where('end_time', '<', time())->delete();

        $recommend = ResourceRecommend::where('end_time', '>', time())->where('type', $type)->order('show_time', 'asc')->limit($limit)->column('rid');

        $where = ['type' => $type];
        if (count($recommend) >= $limit) {
            $where['rid'] = $recommend[0];
        }
        ResourceRecommend::update(['show_time' => time(), 'status' => 1], $where);

//        var_dump($recommend);

        // 每隔320秒更新一次数据
        Cache::set('resource_recommended_' . $type, json_encode($recommend), $time);
    }

    /**
     * 到期会员推送模板消息
     */
    public function expiredMember()
    {
        Log::write('开始给到期会员推送模板消息', 'error');

        $data = UsersMember::alias('m')
            ->join('admin_users u', 'm.uid = u.id', 'left')
            ->where('m.end_time', '<', time())
            ->where('m.is_show', 1)
            ->order('m.end_time', 'desc')
            ->field('u.id,u.openid,u.pub_openid,u.nickname,m.end_time')
            ->select();
        $data = $data ? $data->toArray() : [];
        foreach ($data as $k => $v) {
            $data[$k]['nickname'] = emojiDecode($v['nickname']);
            if ($v['pub_openid']) {
                Log::write('给用户id：' . $v['id'] . '，公众号openId：' . $v['pub_openid'] . '推送会员到期提醒' . json_encode($v) . '', 'error');
                $send = new Wxsend();
                $send->sendMsg($v['pub_openid'], 7, $data[$k]['nickname'], date('Y-m-d H:i:s', $v['end_time']));
            } else {
                Log::write('给用户id：' . $v['id'] . '，公众号openId不存在' . json_encode($v), 'error');
            }
        }

    }
}